package com.bbs.mydigit;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


/**
 * WebView
 * @author songdehuai
 */
public class WebActivity extends Activity {

    WebView webview;

    String Url = "http://bbs.mydigit.cn/";

    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        initTitle();
        initWbeView();

    }



    void initTitle() {
        webview = (WebView) findViewById(R.id.webview);
    }

    @Override
    public void onBackPressed() {
        if (webview.getUrl().equals(Url)) {
            new AlertDialog.Builder(WebActivity.this)
                    .setMessage("确定退出?")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            }).show();
        } else {
            webview.goBack();
        }
    }

    /**
     * 初始化webView
     */
    @SuppressLint("JavascriptInterface")
    void initWbeView() {
        assert webview != null;
        WebSettings settings = webview.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);

        webview.addJavascriptInterface(WebActivity.this, "android");

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                getActionBar().setTitle(view.getTitle());
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.indexOf("http") == 0 || url.indexOf("https") == 0 || url.indexOf("www") == 0) {
                    view.loadUrl(url);
                }
                return true;
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

            }
        });


        webview.loadUrl(Url);
    }


}
